package customer

import (
	"context"
	"fmt"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	"gorm.io/gorm"
	"time"
)

type gfyxCustomerPoolImportRepo struct {
	tenant_db.TenantDB
}

func NewGfyxCustomerPoolImportRepo() CustomerPoolImportRepoIface {
	return &gfyxCustomerPoolImportRepo{}
}

func (r *gfyxCustomerPoolImportRepo) Save(ctx context.Context, po *GfyxCustomerPoolImportPo) (*GfyxCustomerPoolImportPo, error) {
	err := r.GetTenantDB(ctx).Table(po.TableName()).Save(po).Error
	return po, err
}

func (r *gfyxCustomerPoolImportRepo) Update(ctx context.Context, condition, updates map[string]interface{}) error {
	db := r.GetTenantDB(ctx).Table(GfyxCustomerPoolImportPo{}.TableName())
	if ids, ok := condition["ids"]; ok {
		db = db.Where("id in (?)", ids)
		delete(condition, "ids")
	}
	return db.Where(condition).Updates(updates).Error
}

func (r *gfyxCustomerPoolImportRepo) Delete(ctx context.Context, condition map[string]interface{}, operator string) error {
	updates := map[string]interface{}{"is_deleted": constants.IsDeletedTrue, "updated_at": time.Now(), "updated_by": operator}
	return r.Update(ctx, condition, updates)
}

func (r *gfyxCustomerPoolImportRepo) Query(ctx context.Context, condition map[string]interface{}, pageInfo *utils.PageInfo) (int64, []*GfyxCustomerPoolImportPo, error) {
	db := r.GetTenantDB(ctx).Table(GfyxCustomerPoolImportPo{}.TableName()).Where("is_deleted = ?", constants.IsDeletedFalse)

	if keyword, ok := condition["keyword"]; ok {
		db.Where(fmt.Sprintf("company_name like '%%%s%%'", keyword))
		delete(condition, "keyword")
	}
	if st, ok := condition["start_time"]; ok {
		db.Where("created_at >= ?", st)
		delete(condition, "start_time")
	}
	if et, ok := condition["end_time"]; ok {
		db.Where("created_at <= ?", et)
		delete(condition, "end_time")
	}

	db = db.Where(condition)
	var count int64
	var queryList []*GfyxCustomerPoolImportPo
	err := db.Count(&count).Error
	if err != nil {
		return 0, nil, err
	}

	if pageInfo != nil && pageInfo.Page > 0 && pageInfo.PageSize > 0 {
		db = db.Offset((pageInfo.Page - 1) * pageInfo.PageSize).Limit(pageInfo.PageSize)
	}
	if err = db.Order("id desc").Find(&queryList).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return 0, nil, nil
		}
		return 0, nil, err
	}
	return count, queryList, nil
}

func (r *gfyxCustomerPoolImportRepo) Count(ctx context.Context, condition map[string]interface{}) (int64, error) {
	var count int64
	err := r.GetTenantDB(ctx).Table(GfyxCustomerPoolImportPo{}.TableName()).Where(condition).Count(&count).Error
	return count, err
}
